<?php
class RebuildSponsorTree extends BuildTask {
    
    protected $title = 'Rebuild Sponsor Tree';
    
    protected $description = 'Rebuild Sponsor Tree';
    
    function init() {
        parent::init();
        $canAccess = (Director::isDev() || Director::is_cli() || Permission::check("ADMIN"));
        if(!$canAccess) return Security::permissionFailure($this);
    }
    
    public function run($request)
    {
        set_time_limit(0);
        $time = microtime();
        $time = explode(' ', $time);
        $time = $time[1] + $time[0];
        $start = $time;
		
		DB::alteration_message('Start rebuild sponsor tree', 'created');
        
        DB::query("update Sponsor set NLeft = 0, NRight = 0, NLevel = 0");
        $root_id = Distributor::get_id_by_username(Sponsor::get_root_username());
        $root = DataObject::get_one('Sponsor', "MemberID = ".(int)$root_id);
        $root->create_preorderings();
        
        $result = DB::query("select b.Username from Sponsor a inner join Member b on a.MemberID = b.ID where a.NLeft = 0 OR a.NRight = 0 OR a.NLevel = 0");
        
        if(sizeof($result)){
            foreach($result as $data){
                DB::alteration_message(sprintf('Error rebuild sponsor tree (%s)', $data['Username']), 'deleted');
            }
        }
        else{
			DB::alteration_message('Finish rebuild sponsor tree', 'created');
        }
        
        $time = microtime();
        $time = explode(' ', $time);
        $time = $time[1] + $time[0];
        $finish = $time;
        $total_time = round(($finish - $start), 4);
        DB::alteration_message('Process Time - ' . $total_time . ' seconds', 'created');
    }
}

?>